import React, { useRef, useState } from 'react';
import { Button, message, Form, Input, Radio, Spin, TreeSelect, InputNumber } from 'antd';
import { DrawerForm } from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import { PlusOutlined, FormOutlined } from '@ant-design/icons';
import { add, edit, update, getPidList } from '@/services/admin/information/archiveType/api';
interface PorpsType {
  onConfirm: () => void;
  id?: number;
  pid?: number;
  disabled?: boolean;
}
const FormIndex: React.FC<PorpsType> = (porps) => {
  const restFormRef = useRef<ProFormInstance>();
  const [loading, setLoading] = useState(porps.id ? false : true);
  const [pidList, setPidList] = useState<any>([]);
  const [pidListLoading, setPidListLoading] = useState<boolean>(false);
  const { TextArea } = Input;
  const formData: API.AdminArchiveTypeForm = {
    id: null,
    name: '',
    status: 1,
    level: 1,
    pid: 0,
    sort: 1,
    description: '',
  };
  return (
    <DrawerForm<API.BlogAdminArticleTypeForm>
      layout="horizontal"
      labelCol={{ span: 3 }}
      wrapperCol={{ span: 20 }}
      formRef={restFormRef}
      initialValues={formData}
      title={porps.id ? '编辑' : '添加'}
      autoFocusFirstInput
      isKeyPressSubmit
      trigger={
        porps.id ? (
          <Button type="primary" disabled={porps.disabled ? true : false} size="small">
            <FormOutlined />
            编辑
          </Button>
        ) : porps.pid ? (
          <Button type="primary" size="small">
            <PlusOutlined />
            添加子模板
          </Button>
        ) : (
          <Button type="primary">
            <PlusOutlined />
            添加
          </Button>
        )
      }
      drawerProps={{
        forceRender: true,
        destroyOnClose: true,
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [
            ...defaultDoms,
            <Button
              loading={loading ? false : true}
              key="extra-reset"
              onClick={async () => {
                const id = props.form?.getFieldValue('id');
                if (id) {
                  await setLoading(false);
                  const res = await edit(id);
                  if (res.status === 20000) {
                    restFormRef.current?.setFieldsValue(res.data);
                    await setLoading(true);
                  }
                } else {
                  props.reset();
                }
              }}
            >
              重置
            </Button>,
          ];
        },
      }}
      onFinish={async (values: any) => {
        let res: any = {};
        if (porps.id) {
          res = await update(porps.id, values);
        } else {
          res = await add(values);
        }
        if (res.status === 20000) {
          message.success(res.message);
          porps.onConfirm();
          return true;
        }
        return false;
      }}
      onVisibleChange={async (visible) => {
        if (visible) {
          if (porps.pid) {
            await restFormRef.current?.setFieldsValue({ pid: porps.pid });
          }
          if (porps.id) {
            await setLoading(false);
            const res = await edit(porps.id);
            if (res.status === 20000) {
              await restFormRef.current?.setFieldsValue(res.data);
              await setLoading(true);
            }
          }
          const data: { id?: number } = {};
          if (porps.id) {
            data.id = porps.id;
          }
          await setPidListLoading(true);
          const pidRes = await getPidList(data);
          if (pidRes.status == 20000) {
            await setPidListLoading(false);
            await setPidList(pidRes.data);
          }
        }
      }}
    >
      <Spin spinning={loading ? false : true}>
        {loading && (
          <>
            <Form.Item
              label="父级模板"
              name="pid"
              rules={[{ required: true, message: '请选择父级模板' }]}
            >
              <TreeSelect
                treeData={pidList}
                allowClear
                placeholder="请选择父级模板"
                loading={pidListLoading}
              />
            </Form.Item>
            <Form.Item
              label="模板名称"
              name="name"
              rules={[{ required: true, message: '请输入模板名称' }]}
            >
              <Input maxLength={100} allowClear placeholder="请输入模板名称" />
            </Form.Item>

            <Form.Item label="模板描述" name="description">
              <TextArea showCount maxLength={250} placeholder="请输入模板描述" />
            </Form.Item>
            <Form.Item
              name="status"
              label="状态"
              rules={[{ required: true, message: '请选择状态' }]}
            >
              <Radio.Group name="status">
                <Radio value={0}>隐藏</Radio>
                <Radio value={1}>显示</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item label="排序" name="sort" rules={[{ required: true, message: '请输入排序' }]}>
              <InputNumber
                maxLength={11}
                placeholder="请输入排序"
                min={0}
                style={{ width: '100%' }}
              />
            </Form.Item>
          </>
        )}
      </Spin>
    </DrawerForm>
  );
};
export default FormIndex;
